package com.example.library_common.album.media_reader.task;

import android.os.AsyncTask;

import com.example.library_common.album.bean.AlbumFile;
import com.example.library_common.album.bean.AlbumFolder;
import com.example.library_common.album.bean.FunctionBean;
import com.example.library_common.album.constant.AlbumMedia;
import com.example.library_common.album.media_reader.AlbumMediaReader;
import com.example.library_common.album.media_reader.AllMediaReader;
import com.example.library_common.album.media_reader.ImageMediaReader;
import com.example.library_common.album.media_reader.VideoMediaReader;

import java.util.ArrayList;
import java.util.List;

public class MediaTask extends AsyncTask<Void, Void, ResultWrapper> {

    private FunctionBean functionBean;

    public MediaTask(FunctionBean functionBean) {
        this.functionBean = functionBean;
    }

    private Callback mCallback;

    public MediaTask setCallback(Callback callback) {
        this.mCallback = callback;
        return this;
    }

    @Override
    protected ResultWrapper doInBackground(Void... voids) {

        ResultWrapper wrapper = new ResultWrapper();

        if (functionBean == null) return wrapper;

        String mediaType = functionBean.getMediaType();
        AlbumMediaReader reader = null;
        switch (mediaType) {
            case AlbumMedia.MEDIA_FOR_IMAGE:
                reader = new ImageMediaReader();
                break;
            case AlbumMedia.MEDIA_FOR_VIDEO:
                reader = new VideoMediaReader();
                break;
            case AlbumMedia.MEDIA_FOR_ALL:
                reader = new AllMediaReader();
                break;
        }
        if (reader == null) {
            return wrapper;
        }
        List<AlbumFolder> allMediaFile = reader.getAllMediaFile();

        List<AlbumFile> checkedFiles = functionBean.getCheckedFiles();

        List<AlbumFile> albumFiles = allMediaFile.get(0).getAlbumFiles();

        for (AlbumFile checkAlbumFile : checkedFiles) {
            for (int i = 0; i < albumFiles.size(); i++) {
                AlbumFile albumFile = albumFiles.get(i);
                if (checkAlbumFile.equals(albumFile)) {
                    albumFile.setChecked(true);
//                    checkedFiles.add(albumFile);
                }
            }
        }

        wrapper.getAlbumFolders().addAll(allMediaFile);

        return wrapper;
    }

    @Override
    protected void onPostExecute(ResultWrapper wrapper) {
        super.onPostExecute(wrapper);
        if (mCallback != null) {
            mCallback.onScanCallback(wrapper.getAlbumFolders() );
        }

    }
}
